<?php

namespace app\admin\model\scanwork;

use think\Model;

class OrderCost extends Model
{
    protected $name = 'scanwork_order_cost';
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function order()
    {
        return $this->belongsTo('Order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function product()
    {
        return $this->belongsTo('Product', 'product_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 计算订单总成本
     */
    public function calculateTotalCost()
    {
        $this->total_cost = $this->material_cost + $this->labor_cost + 
                           $this->equipment_cost + $this->energy_cost + 
                           $this->quality_cost + $this->overhead_cost;
        
        if ($this->quantity > 0) {
            $this->unit_cost = $this->total_cost / $this->quantity;
        }
        
        if ($this->selling_price > 0) {
            $this->profit = ($this->selling_price * $this->quantity) - $this->total_cost;
            $this->profit_rate = ($this->profit / $this->total_cost) * 100;
        }
        
        return $this->total_cost;
    }
}

